import { defineStore } from 'pinia';
import _ from 'lodash';
import { TYPE_APP_CONFIG } from '@/system/typeConsts';

export const useAppStore = defineStore('app', {
    state: () => ({
        requestNum: 0,
        windowHeight: 0,
        appConfig: {},
        appRemoteConfig: [],
        activateRecord: {
            userName: false,
            diffDay: 0,
            effDate: '',
            activateKey: '',
            vipLevel: '1',
            isAct: true,
        },
        socketState: 0, // socketState是否连接 0 否 1 是
        isAdmin: '0', // 是否是管理员
        roleList: [], // 角色列表
        permissionList: [], // 权限列表
        htjar: { port: 0, state: 0 }, // state 0 为未启动 1 启动
        releaseNoteVisible: false, // 更新提示
        appUpdatePath: '', // app的更新地址
    }),
    actions: {
        setRequestNum(num) {
            let stateRequestNum = this.requestNum + num;
            // console.log('this.requestNum,num', this.requestNum, num, stateRequestNum);
            if (stateRequestNum <= 0) {
                stateRequestNum = 0;
            }
            this.requestNum = stateRequestNum;
        },
        setWindowHeight(wHeight) {
            this.windowHeight = wHeight;
        },
        setActivateRecord(activateRecord) {
            this.activateRecord = activateRecord;
            this.isAdmin = activateRecord.isAdmin || '0';
            this.roleList = activateRecord.roleList || [];
            this.permissionList = activateRecord.permissionList || [];
        },
        async readAppRemoteConfig() {
            try {
                // 远程参数
                let appConfigRes = await getkrUserParamList({ userId: this.activateRecord.id });
                let krUserParamList = commonResponseDeal(appConfigRes);
                console.log('krUserParamList:', krUserParamList);
                // 获取缓存中的参数
                let krUserParamListCache = await window.jsonStorage.getJsonCache('krUserParamList');
                if (krUserParamListCache && krUserParamListCache.length > 0) {
                    for (let i = 0; i < krUserParamList.length; i++) {
                        let item = krUserParamList[i];
                        if (item.autoEdit === '1') {
                            // 找到缓存中的数据，使用缓存数据
                            let cacheItem = _.find(krUserParamListCache, { paramCode: item.paramCode });
                            if (cacheItem) {
                                item.paramValue = cacheItem.paramValue;
                            }
                        }
                    }
                }
                // 缓存到路径里面一份
                this.appRemoteConfig = krUserParamList;
                // 往主进程发送配置消息
                // window.menuTool.app_remote_config_sync(krUserParamListCache).then();
                await window.jsonStorage.writeJsonCache('krUserParamList', krUserParamList);
            } catch (e) {
                LOGGER.error('获取远程参数报错：', e.toString());
                let krUserParamListCache = await window.jsonStorage.getJsonCache('krUserParamList');
                console.log('krUserParamListCache:', krUserParamListCache);
                if (krUserParamListCache) {
                    this.appRemoteConfig = krUserParamListCache;
                    // window.menuTool.app_remote_config_sync(krUserParamListCache).then();
                }
            }
        },
        writeHtjar(htjar) {
            if (htjar.state) {
                window.sysUrl = `http://localhost:${htjar.port}`;
            }
            this.htjar = htjar;
        },
        async readAppConfig() {
            let appConfigRes = await window.dbkrJsonParam.getKrJsonParamAll(TYPE_APP_CONFIG);
            console.log('appConfigRes', appConfigRes);
            if (appConfigRes && appConfigRes.length > 0) {
                let appConfig = appConfigRes[0];

                if (appConfig && appConfig.json_str) {
                    appConfig = Object.assign({}, appConfig, JSON.parse(appConfig.json_str));
                    delete appConfig.json_str;
                }
                this.appConfig = appConfig;
            }
        },
        async writeAppConfig({ appConfig, remoteParamList }) {
            if (!appConfig) {
                return;
            }
            let updObj = {
                id: appConfig.id,
                type: TYPE_APP_CONFIG,
                json_str: JSON.stringify(appConfig),
                add_time: appConfig.add_time,
                rsrv_str1: '',
            };
            let appConfigTmp = await window.dbkrJsonParam.saveOrUpdateById(updObj);
            console.log('appConfigTmp----writeAppConfig', appConfigTmp);
            if (appConfigTmp && appConfigTmp.json_str) {
                appConfigTmp = Object.assign({}, appConfigTmp, JSON.parse(appConfigTmp.json_str));
                delete appConfigTmp.json_str;
            }
            this.appConfig = appConfigTmp;
            // 保存远程参数
            if (remoteParamList) {
                // 缓存到路径里面一份
                this.appRemoteConfig = remoteParamList;
                await window.jsonStorage.writeJsonCache('krUserParamList', remoteParamList);
            }
        },
    },
});
